#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-hostname
# BEFORE: hostname

. /etc/rc.freenas

generate_hostname()
{
	local IFS="|"
	local id gc_hostname gc_domain hostname_field
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT

	if [ "$(ha_node)" = "B" ]; then
		hostname_field="gc_hostname_b"
	else
		hostname_field="gc_hostname"
	fi

	id="$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
            "SELECT id FROM network_globalconfiguration ORDER BY -id LIMIT 1")"
	gc_hostname="$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
            "SELECT ${hostname_field} FROM network_globalconfiguration ORDER BY -id LIMIT 1")"
	gc_domain="$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
            "SELECT gc_domain FROM network_globalconfiguration ORDER BY -id LIMIT 1")"

	cp /conf/base/etc/hosts /etc/hosts
	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
		"SELECT gc_hosts FROM network_globalconfiguration WHERE id = ${id}" >> /etc/hosts

	if dirsrv_enabled nis; then
		echo -e "127.0.0.1\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		echo -e "::1\t\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		echo nis >> /etc/host.conf
		echo "${NIS_HOSTSSTR}" >> /etc/hosts
	elif dirsrv_enabled activedirectory; then
		local domainname
		local netbiosname
		local netbiosname_field

		if [ "$(ha_node)" = "B" ]; then
			netbiosname_field="cifs_srv_netbiosname_b"
		else
			netbiosname_field="cifs_srv_netbiosname"
		fi
		netbiosname="$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT ${netbiosname_field} FROM services_cifs ORDER BY -id LIMIT 1"|tr A-Z a-z)"

		${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
		"SELECT ad_domainname from directoryservice_activedirectory ORDER BY -id LIMIT 1" | \
		while read -r domainname; do
			domainname="$(echo "${domainname}"|tr A-Z a-z)"

			echo -e "127.0.0.1\t"${netbiosname}.${domainname}" "${netbiosname}"" >> /etc/hosts
			echo -e "::1\t\t"${netbiosname}.${domainname}" "${netbiosname}"" >> /etc/hosts
		done
	else
		echo -e "127.0.0.1\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		echo -e "::1\t\t${gc_hostname}.${gc_domain} ${gc_hostname}" >> /etc/hosts
		local tmpfile="$(mktemp /tmp/.XXXXXX)"
		grep -Ev '^nis' /etc/host.conf > "${tmpfile}" 2> /dev/null
		mv "${tmpfile}" /etc/host.conf
		chmod 644 /etc/host.conf
	fi
}

name="ix-hostname"
start_cmd='generate_hostname'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
